<template>
  <div class="wrapper">
    <!-- 头部导航 -->
    <header>
      <p>饿了么</p>
    </header>

    <!-- 订单状态切换 -->
    <div class="order-tabs">
      <div class="tab-item active">全部</div>
      <div class="tab-item">待评价</div>
      <div class="tab-item">退款</div>
    </div>

    <!-- 订单列表 -->
    <ul class="order-list">
      <li v-for="order in orderList" :key="order.orderId" @click="toggleOrder(order)">
        <!-- 商家信息 -->
        <div class="business-header">
          <div class="business-info">
            <img :src="order.business?.businessImg" class="business-img">
            <div class="business-detail">
              <h3>{{order.business?.businessName}}</h3>
              <p class="order-time">{{formatTime(order.orderDate)}}</p>
            </div>
          </div>
          <div class="order-status">{{order.orderState === 0 ? '已取消' : '已送达'}}</div>
        </div>

        <!-- 订单详情 -->
        <div class="order-detail" v-if="order.isExpanded && order.orderDetailetList">
          <div class="food-list">
            <div class="food-item" v-for="detail in order.orderDetailetList" :key="detail.odId">
              <img :src="detail.food.foodImg" class="food-img">
              <div class="food-info">
                <span class="food-name">{{detail.food.foodName}}</span>
                <div class="food-price-info">
                  <span class="food-quantity">x{{detail.quantity}}</span>
                  <span class="food-price">¥{{detail.food.foodPrice}}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 订单底部 -->
        <div class="order-footer">
          <div class="order-total">
            <span>共{{order.orderDetailetList?.length || 1}}件</span>
            <span class="price">¥{{order.orderTotal}}</span>
          </div>
          <div class="order-actions">
            <button class="action-btn" @click.stop="toPayment(order.orderId)">去支付</button>
            <button class="action-btn reorder" @click.stop>再来一单</button>
          </div>
        </div>
      </li>
    </ul>

    <Footer />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import Footer from './Footer.vue'

const router = useRouter()
const orderList = ref([])

// 获取订单列表
const loadOrders = async () => {
  try {
    const token = sessionStorage.getItem('token')
    const user = JSON.parse(sessionStorage.getItem('user'))
    if (!token || !user) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    const response = await request({
      url: '/OrdersController/listOrdersByUserId',
      method: 'get',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      params: {
        userId: user.userId
      }
    })

    // 初始化订单列表，添加 isExpanded 属性
    orderList.value = response.data.map(order => ({
      ...order,
      isExpanded: false
    }))
  } catch (error) {
    console.error('获取订单列表错误:', error)
    if (error.response?.status === 401 || error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('user')
      router.push('/login')
    } else {
      ElMessage.error('获取订单列表失败')
    }
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
}

// 去支付
const toPayment = (orderId) => {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  router.push({
    path: '/payment',
    query: { orderId }
  })
}

// 切换订单展开状态
const toggleOrder = async (order) => {
  // 如果已经有订单详情数据，直接切换展开状态
  if (order.isExpanded) {
    order.isExpanded = false
    return
  }

  try {
    const token = sessionStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    // 获取订单详情
    const response = await request({
      url: '/OrdersController/getOrdersById',
      method: 'get',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      params: {
        orderId: order.orderId
      }
    })

    if (response.data) {
      // 更新订单信息
      order.business = response.data.business
      order.orderDetailetList = response.data.orderDetailetList
      order.isExpanded = true
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    if (error.response?.status === 401 || error.response?.status === 403) {
      ElMessage.error('登录已过期，请重新登录')
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('user')
      router.push('/login')
    } else {
      ElMessage.error('获取订单详情失败')
    }
  }
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.wrapper {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 50px;
}

header {
  background: #fff;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 500;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.order-tabs {
  margin-top: 44px;
  display: flex;
  background: #fff;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 14px;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #0097FF;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -12px;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 2px;
  background: #0097FF;
}

.order-list {
  padding: 12px;
}

.order-list li {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  overflow: hidden;
}

.business-header {
  padding: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
}

.business-info {
  display: flex;
  align-items: center;
}

.business-img {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 10px;
}

.business-detail h3 {
  font-size: 15px;
  color: #333;
  margin-bottom: 4px;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.order-status {
  font-size: 13px;
  color: #999;
}

.order-detail {
  padding: 12px;
  border-bottom: 1px solid #f5f5f5;
}

.food-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.food-img {
  width: 35px;
  height: 35px;
  border-radius: 4px;
  margin-right: 10px;
}

.food-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.food-name {
  font-size: 14px;
  color: #333;
}

.food-quantity {
  font-size: 13px;
  color: #666;
  margin-right: 8px;
}

.food-price {
  font-size: 13px;
  color: #333;
}

.order-footer {
  padding: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f5f5f5;
}

.order-total {
  font-size: 13px;
  color: #666;
}

.order-total .price {
  margin-left: 8px;
  font-weight: 500;
  color: #333;
}

.action-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 15px;
  font-size: 13px;
  color: #666;
  background: #fff;
}

.action-btn.reorder {
  border-color: #0097FF;
  color: #0097FF;
}

/* 支付按钮样式 */
.action-btn:active {
  opacity: 0.8;
}

/* 添加过渡动画 */
.order-detail {
  transition: all 0.3s ease;
}

.order-actions {
  display: flex;
  gap: 10px;
}
</style>